<?php
namespace app\admin\controller;

use app\common\BaseAdminController;
use think\facade\Db;

class User extends BaseAdminController
{

    public function list($pageNum = 1, $pageSize = 10, $username = "")
    {
        // 查询用户列表
        $userList = Db::table('user')->where('username', 'like', '%' . $username . '%')->page($pageNum, $pageSize)->select();
        // 查询用户总数
        $total = Db::table('user')->where('username', 'like', '%' . $username . '%')->count();
        // 返回结果
        return json([
            'code'    => 200,
            'message' => 'success',
            'data'    => [
                'list'  => $userList,
                'total' => $total,
            ],
        ]);
    }

    public function add()
    {
        $data = $this->request->post();
        // 验证参数
        $validate = new \app\validate\User();
        if (! $validate->check($data)) {
            return json(['code' => 400, 'msg' => $validate->getError()]);
        }

        // 检查用户名是否已存在
        $existingUser = Db::table('user')->where('username', $data['username'])->find();
        if ($existingUser) {
            return json(['code' => 400, 'msg' => '用户名已存在']);
        }

        // 插入新用户
        $insertData = [
            'username' => $data['username'],
            'password' => password_hash($data['password'], PASSWORD_DEFAULT), // 哈希密码
            'nickname' => $data['nickname'] ?? '',                            // 昵称
            'avatar'   => $data['avatar'] ?? '',                              // 头像
        ];
        Db::table('user')->insert($insertData);

        return json([
            'code'    => 200,
            'message' => 'success',
            'data'    => null,
        ]);
    }

    public function update()
    {
        $data = $this->request->post();
        $id   = $data['id'];

        // 验证参数
        $validate = new \app\validate\UserEdit();
        if (! $validate->check($data)) {
            return json(['code' => 400, 'msg' => $validate->getError()]);
        }

        $user = Db::table('user')->where('id', $id)->find();

        if ($user) {
            // $updateData从$data中提取字段 并进行密码哈希
            $updateData = [
                // 'password' => password_hash($data['password'], PASSWORD_DEFAULT),
                "username" => $data['username'],
                "nickname" => $data['nickname'] ?? $user['nickname'],
                "avatar"   => $data['avatar'] ?? $user['avatar'],
            ];

            Db::table('user')->where('id', $id)->update($updateData);

            return json([
                'code'    => 200,
                'message' => 'success',
                'data'    => null,
            ]);
        } else {
            return json([
                'code'    => 400,
                'message' => '用户不存在',
                'data'    => null,
            ]);
        }
    }
}
